<template>
  <div class="telemedicine-room">
    <!-- 顶部工具栏 -->
    <el-header class="toolbar">
      <el-row :gutter="10" justify="space-between" align="middle">
        <el-col :span="6">
          <h2>多学科会诊室</h2>
        </el-col>
        <el-col :span="12">
          <el-button-group>
            <el-button type="primary" @click="toggleMute">
              {{ isMuted ? '取消静音' : '静音' }}
            </el-button>
            <el-button type="primary" @click="toggleVideo">
              {{ isVideoOff ? '开启摄像头' : '关闭摄像头' }}
            </el-button>
            <el-button type="success" @click="startScreenShare" :disabled="isScreenSharing">
              开始共享屏幕
            </el-button>
            <el-button type="warning" @click="stopScreenShare" :disabled="!isScreenSharing">
              停止共享屏幕
            </el-button>
            <el-button type="danger" @click="startRecording">
              开始录屏
            </el-button>
            <el-button type="danger" @click="stopRecording">
              停止录屏
            </el-button>
          </el-button-group>
        </el-col>
        <el-col :span="6" class="text-right">
          <el-button type="info" @click="exportNotes">导出笔记</el-button>
        </el-col>
      </el-row>
    </el-header>

    <el-container class="main-content">
      <!-- 左侧：文件列表和笔记区域 -->
      <el-aside width="300px" class="left-panel">
        <el-tabs type="border-card" v-model="activeLeftTab">
          <!-- 文件共享 Tab -->
          <el-tab-pane label="文件共享" name="files">
            <div class="file-upload-area" @drop.prevent="handleFileDrop" @dragover.prevent>
              <p>拖拽文件到此处上传</p>
              <input type="file" ref="fileInput" @change="handleFileSelect" style="display: none;" multiple>
              <el-button @click="$refs.fileInput.click()">选择文件</el-button>
            </div>
            <el-input
              v-model="fileSearch"
              placeholder="搜索文件"
              prefix-icon="el-icon-search"
              size="small"
              style="margin-top: 10px;"
            />
            <el-table :data="filteredFiles" size="mini" style="margin-top: 10px;" max-height="200">
              <el-table-column prop="name" label="文件名" show-overflow-tooltip>
                <template #default="{ row }">
                  <a :href="row.url" target="_blank">{{ row.name }}</a>
                </template>
              </el-table-column>
              <el-table-column prop="size" label="大小" width="80">
                <template #default="{ row }">
                  {{ formatFileSize(row.size) }}
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>

          <!-- 笔记 Tab -->
          <el-tab-pane label="会议笔记" name="notes">
            <el-input
              type="textarea"
              v-model="meetingNotes"
              placeholder="在此记录会议内容..."
              :rows="15"
              @input="saveNotesLocally"
            ></el-input>
          </el-tab-pane>
        </el-tabs>
      </el-aside>

      <!-- 中间：主视频区和参与者列表 -->
      <el-main class="center-panel">
        <el-row :gutter="10" style="height: 100%;">
          <!-- 主视频显示区 -->
          <el-col :span="18" class="video-main">
            <div class="main-video-container">
              <video ref="mainVideo" autoplay playsinline class="main-video"></video>
              <div class="main-video-overlay">
                <span>{{ activeSpeaker || '请选择发言人' }}</span>
              </div>
            </div>
          </el-col>

          <!-- 参与者列表 -->
          <el-col :span="6" class="participants-list">
            <h4>参会者 ({{ participants.length }})</h4>
            <div class="participant-item" v-for="participant in participants" :key="participant.id">
              <div class="participant-video-wrapper">
                <video :ref="el => setParticipantVideoRef(el, participant.id)" autoplay playsinline muted v-if="participant.id === localUserId"></video>
                <video :ref="el => setParticipantVideoRef(el, participant.id)" autoplay playsinline v-else></video>
                <div class="participant-name">{{ participant.name }}</div>
                <div class="participant-status">
                  <i :class="participant.isMuted ? 'el-icon-mic-off' : 'el-icon-mic'"></i>
                </div>
              </div>
            </div>
          </el-col>
        </el-row>
      </el-main>
    </el-container>

    <!-- 底部：AI纪要展示区 -->
    <el-footer class="ai-summary-footer">
      <h4>AI会议纪要</h4>
      <div class="summary-content" ref="summaryContent">
        <p v-for="(item, index) in aiSummary" :key="index">{{ item }}</p>
      </div>
    </el-footer>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, onBeforeUnmount, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// 模拟数据和状态
const activeLeftTab = ref('files')
const fileSearch = ref('')
const meetingNotes = ref('')
const aiSummary = ref([
  '会议开始于 10:00 AM',
  '医生A提出初步诊断...',
  '医生B建议进行进一步检查...',
  // 更多模拟纪要...
])
const activeSpeaker = ref('医生A')
const isMuted = ref(false)
const isVideoOff = ref(false)
const isScreenSharing = ref(false)
const isRecording = ref(false)
const mediaRecorder = ref(null)
const recordedChunks = ref([])

// 模拟文件列表
const files = ref([
  { id: 1, name: '病历报告.pdf', size: 2048000, url: '#' },
  { id: 2, name: '检查影像.jpg', size: 5120000, url: '#' },
  { id: 3, name: '治疗方案.docx', size: 1024000, url: '#' },
])

const filteredFiles = computed(() => {
  return files.value.filter(file =>
    file.name.toLowerCase().includes(fileSearch.value.toLowerCase())
  )
})

// 模拟参与者列表
const participants = ref([
  { id: 'local-user', name: '我 (医生)', isMuted: false },
  { id: 'user-2', name: '医生A', isMuted: true },
  { id: 'user-3', name: '医生B', isMuted: false },
  { id: 'user-4', name: '专家C', isMuted: false },
  // ... 更多参与者
])

const localUserId = 'local-user'

// 视频引用
const mainVideo = ref(null)
const participantVideoRefs = reactive({})

const setParticipantVideoRef = (el, id) => {
  if (el) {
    participantVideoRefs[id] = el
  }
}

// 格式化文件大小
const formatFileSize = (bytes) => {
  if (bytes === 0) return '0 Bytes'
  const k = 1024
  const sizes = ['Bytes', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

// 文件处理
const handleFileDrop = (event) => {
  const droppedFiles = Array.from(event.dataTransfer.files)
  // 模拟文件上传和分发
  droppedFiles.forEach(file => {
    files.value.push({
      id: Date.now() + Math.random(),
      name: file.name,
      size: file.size,
      url: URL.createObjectURL(file) // 仅作演示，实际应上传到服务器
    })
  })
  ElMessage.success(`成功上传 ${droppedFiles.length} 个文件`)
}

const handleFileSelect = (event) => {
  const selectedFiles = Array.from(event.target.files)
  selectedFiles.forEach(file => {
    files.value.push({
      id: Date.now() + Math.random(),
      name: file.name,
      size: file.size,
      url: URL.createObjectURL(file)
    })
  })
  ElMessage.success(`成功选择 ${selectedFiles.length} 个文件`)
  // 重置input value以便再次选择相同文件
  event.target.value = ''
}

// 视频控制
const toggleMute = () => {
  isMuted.value = !isMuted.value
  // 实际应用中需要操作本地音频轨道
  ElMessage.info(isMuted.value ? '已静音' : '已取消静音')
}

const toggleVideo = () => {
  isVideoOff.value = !isVideoOff.value
  // 实际应用中需要操作本地视频轨道
  ElMessage.info(isVideoOff.value ? '已关闭摄像头' : '已开启摄像头')
}

// 屏幕共享 (模拟)
const startScreenShare = () => {
  isScreenSharing.value = true
  ElMessage.success('开始共享屏幕')
  // 实际应用中需要获取屏幕媒体流并替换主视频流
}

const stopScreenShare = () => {
  isScreenSharing.value = false
  ElMessage.info('已停止共享屏幕')
  // 实际应用中需要恢复主视频流
}

// 录屏 (模拟)
const startRecording = async () => {
  try {
    // 实际应用中需要获取包含所有视频流的媒体流进行录制
    // 这里仅作演示
    isRecording.value = true
    recordedChunks.value = []
    ElMessage.success('开始录屏')
  } catch (err) {
    console.error("录屏启动失败:", err)
    ElMessage.error('录屏启动失败')
  }
}

const stopRecording = () => {
  isRecording.value = false
  // 模拟生成并下载录像文件
  const blob = new Blob(recordedChunks.value, { type: 'video/webm' })
  const url = URL.createObjectURL(blob)
  const a = document.createElement('a')
  a.style.display = 'none'
  a.href = url
  a.download = 'meeting-recording.webm'
  document.body.appendChild(a)
  a.click()
  window.URL.revokeObjectURL(url)
  ElMessage.info('录屏已停止并下载')
}

// 笔记处理
const saveNotesLocally = () => {
  localStorage.setItem('meetingNotes', meetingNotes.value)
}

const exportNotes = () => {
  // 模拟导出为文本文件
  const blob = new Blob([meetingNotes.value], { type: 'text/plain' })
  const url = URL.createObjectURL(blob)
  const a = document.createElement('a')
  a.style.display = 'none'
  a.href = url
  a.download = 'meeting-notes.txt'
  document.body.appendChild(a)
  a.click()
  window.URL.revokeObjectURL(url)
  ElMessage.success('笔记已导出')
}

// 模拟获取本地媒体流
const getLocalStream = async () => {
  try {
    const constraints = { video: true, audio: true }
    const stream = await navigator.mediaDevices.getUserMedia(constraints)
    if (participantVideoRefs[localUserId]) {
       participantVideoRefs[localUserId].srcObject = stream
    }
    // 通常还需要将此流添加到 RTCPeerConnection 中
  } catch (err) {
    console.error('获取本地媒体流失败:', err)
    ElMessage.error('无法访问摄像头或麦克风')
  }
}

// 滚动AI纪要到底部
const scrollToBottom = () => {
  nextTick(() => {
    const container = this.$refs.summaryContent
    if (container) {
      container.scrollTop = container.scrollHeight
    }
  })
}

onMounted(() => {
  // 加载本地保存的笔记
  const savedNotes = localStorage.getItem('meetingNotes')
  if (savedNotes) {
    meetingNotes.value = savedNotes
  }

  // 模拟初始化本地视频流
  getLocalStream()

  // 模拟定期更新AI纪要
  const summaryInterval = setInterval(() => {
    if (aiSummary.value.length < 20) { // 限制条目数
      aiSummary.value.push(`[${new Date().toLocaleTimeString()}] 新的会议要点...`)
      scrollToBottom()
    }
  }, 10000)

  // 组件卸载前清理
  onBeforeUnmount(() => {
    clearInterval(summaryInterval)
    // 停止所有媒体流
    Object.values(participantVideoRefs).forEach(video => {
      if (video && video.srcObject) {
        const tracks = video.srcObject.getTracks();
        tracks.forEach(track => track.stop());
      }
    });
  })
})
</script>

<style scoped>
.telemedicine-room {
  height: 100vh;
  display: flex;
  flex-direction: column;
  font-family: 'Helvetica Neue', Helvetica, 'PingFang SC', 'Hiragino Sans GB', Arial, sans-serif;
  background: linear-gradient(135deg, #f5f7fa 0%, #e4e7f4 100%);
}

.toolbar {
  background: linear-gradient(90deg, #2c3e50 0%, #4a6491 100%);
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  padding: 15px 25px;
  color: white;
  border: none;
}

.toolbar h2 {
  margin: 0;
  font-weight: 600;
  font-size: 1.5rem;
  letter-spacing: 0.5px;
}

.toolbar .el-button {
  border-radius: 6px;
  transition: all 0.3s ease;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.toolbar .el-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
}

.toolbar .el-button-group {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.toolbar .el-button-group .el-button {
  border-radius: 6px !important;
  margin: 0;
}

.text-right {
  text-align: right;
}

.main-content {
  flex: 1;
  overflow: hidden;
  padding: 20px;
  gap: 20px;
}

.left-panel {
  background: rgba(255, 255, 255, 0.85);
  backdrop-filter: blur(10px);
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  padding: 20px;
  overflow-y: auto;
  border: 1px solid rgba(255, 255, 255, 0.5);
  height: calc(100vh - 250px);
}

.el-tabs--border-card {
  border: none;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.06);
  border-radius: 10px;
  overflow: hidden;
}

.el-tabs__header {
  background: #f8f9fc;
  margin: 0;
}

.el-tabs__item {
  height: 48px;
  line-height: 48px;
  font-weight: 500;
  color: #606266;
}

.el-tabs__item.is-active {
  background: white;
  color: #409eff;
  border-bottom-color: #409eff;
}

.file-upload-area {
  border: 2px dashed #c0c4cc;
  border-radius: 10px;
  padding: 25px;
  text-align: center;
  color: #909399;
  cursor: pointer;
  transition: all 0.3s ease;
  background: #fafbfd;
  margin-bottom: 20px;
}

.file-upload-area:hover {
  border-color: #409eff;
  background: #f0f8ff;
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(64, 158, 255, 0.1);
}

.file-upload-area i {
  font-size: 48px;
  margin-bottom: 10px;
  color: #c0c4cc;
}

.file-upload-area:hover i {
  color: #409eff;
}

.center-panel {
  padding: 0;
  background: transparent;
  height: calc(100vh - 250px);
}

.video-main {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.main-video-container {
  flex: 1;
  background: linear-gradient(135deg, #1a2a4c 0%, #2c3e50 100%);
  position: relative;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.2);
  display: flex;
  align-items: center;
  justify-content: center;
}

.main-video {
  width: 100%;
  height: 100%;
  object-fit: contain;
  background: #000;
}

.main-video-overlay {
  position: absolute;
  bottom: 20px;
  left: 20px;
  background-color: rgba(0, 0, 0, 0.6);
  color: white;
  padding: 8px 16px;
  border-radius: 20px;
  font-size: 14px;
  font-weight: 500;
  backdrop-filter: blur(5px);
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.2);
  max-width: 70%;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.participants-list {
  background: rgba(255, 255, 255, 0.85);
  backdrop-filter: blur(10px);
  border-radius: 12px;
  padding: 20px;
  overflow-y: auto;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  border: 1px solid rgba(255, 255, 255, 0.5);
  height: 100%;
}

.participants-list h4 {
  margin-top: 0;
  margin-bottom: 20px;
  color: #303133;
  font-weight: 600;
  font-size: 1.1rem;
  padding-bottom: 12px;
  border-bottom: 1px solid #ebeef5;
}

.participant-item {
  margin-bottom: 15px;
  border-radius: 10px;
  overflow: hidden;
  transition: all 0.3s ease;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  background: white;
}

.participant-item:hover {
  transform: translateY(-3px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.participant-video-wrapper {
  position: relative;
  width: 100%;
  padding-top: 75%; /* 4:3 Aspect Ratio */
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 8px;
  overflow: hidden;
}

.participant-video-wrapper video {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.participant-name {
  position: absolute;
  bottom: 10px;
  left: 10px;
  background-color: rgba(0, 0, 0, 0.7);
  color: white;
  padding: 5px 10px;
  border-radius: 15px;
  font-size: 12px;
  font-weight: 500;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 70%;
  backdrop-filter: blur(5px);
}

.participant-status {
  position: absolute;
  top: 10px;
  right: 10px;
  background-color: rgba(0, 0, 0, 0.7);
  color: white;
  padding: 5px;
  border-radius: 50%;
  font-size: 14px;
  width: 24px;
  height: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
  backdrop-filter: blur(5px);
}

.ai-summary-footer {
  background: rgba(255, 255, 255, 0.85);
  backdrop-filter: blur(10px);
  border-top: 1px solid rgba(235, 238, 245, 0.5);
  padding: 20px;
  height: 180px;
  display: flex;
  flex-direction: column;
  border-radius: 12px 12px 0 0;
  box-shadow: 0 -2px 12px rgba(0, 0, 0, 0.05);
  margin: 0 20px;
  border: 1px solid rgba(255, 255, 255, 0.5);
  border-bottom: none;
}

.ai-summary-footer h4 {
  margin-top: 0;
  margin-bottom: 12px;
  color: #303133;
  font-weight: 600;
  font-size: 1.1rem;
}

.summary-content {
  flex: 1;
  overflow-y: auto;
  background: rgba(245, 247, 250, 0.6);
  padding: 15px;
  border-radius: 8px;
  font-size: 14px;
  line-height: 1.6;
  box-shadow: inset 0 2px 4px rgba(0, 0, 0, 0.03);
}

.summary-content p {
  margin: 0 0 8px 0;
  padding: 8px 12px;
  background: white;
  border-radius: 6px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
  animation: fadeIn 0.3s ease;
  border-left: 3px solid #409eff;
}

@keyframes fadeIn {
  from { opacity: 0; transform: translateY(10px); }
  to { opacity: 1; transform: translateY(0); }
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .main-content {
    flex-direction: column;
    gap: 15px;
  }
  
  .left-panel {
    width: 100% !important;
    height: auto;
  }
  
  .center-panel {
    height: 500px;
  }
  
  .participants-list {
    height: auto;
    max-height: 200px;
  }
}

/* 滚动条样式优化 */
::-webkit-scrollbar {
  width: 6px;
  height: 6px;
}

::-webkit-scrollbar-thumb {
  background: #c0c4cc;
  border-radius: 3px;
}

::-webkit-scrollbar-thumb:hover {
  background: #909399;
}

::-webkit-scrollbar-track {
  background: rgba(245, 247, 250, 0.5);
  border-radius: 3px;
}
</style>



